package com.pateo.springcloudgoods.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class MybatisConfig {

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        //mybatis 配置
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setCacheEnabled(true);
        configuration.setDefaultStatementTimeout(3000);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setUseGeneratedKeys(true);
        sessionFactory.setConfiguration(configuration);
        //扫描mybatis的xml文件
        List<String> mapperXmlLocations = new ArrayList<>(16);
        mapperXmlLocations.add("classpath*:com/pateo/springcloudgoods/dao/mapper/**/*Mapper.xml");
        List<Resource> resourceList = new ArrayList<>(256);
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources;
        for(String url : mapperXmlLocations){
            resources = pathMatchingResourcePatternResolver.getResources(url);
            if(resources != null && resources.length > 0){
                Arrays.stream(resources).forEach(resource -> resourceList.add(resource));
            }
        }
        sessionFactory.setMapperLocations(resourceList.toArray(new Resource[resourceList.size()]));
        return sessionFactory.getObject();
    }

    @Bean(name = "mapperScannerConfigurer")
    public MapperScannerConfigurer mapperScannerConfigurer() {
        StringBuilder basePackages = new StringBuilder(512);
        //扫描mapper的Java接口
        basePackages
                .append("com.pateo.springcloudgoods.dao.mapper").append(System.lineSeparator());
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage(basePackages.toString());
        return mapperScannerConfigurer;
    }

}
